package logic

import (
	"community/models/mysqlinit"
	"community/models/redisinit"
	"community/pkg"
	"context"
	"fmt"

	"community/communityrpc/communityrpc"
	"community/communityrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *communityrpc.LoginRequest) (*communityrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysqlinit.User

	mysqlinit.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("账号未注册，请重新输入")
	}
	if user.Password != pkg.Md5pass(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}

	result, _ := redisinit.Client.Get("SendSms" + in.Account + "Login").Result()
	if in.SendSms != result {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	return &communityrpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
